package app.backend.utils;

import app.backend.entity.AppClientUser;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import app.backend.constant.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangjianbin
 * @since 2022/8/20 11:48
 */
@Slf4j
public class SessionUtils {

    private static int validityDuration = 24 * 60 * 60;

    private static RedisUtils redisUtils = SpringUtil.getBean(RedisUtils.class);

    public static String saveSessionInfo(AppClientUser user) {
        Map<String, String> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getNickname());
        String lastToken = redisUtils.get(RedisKey.USER_LOGIN_PREFIX + user.getId());
        if (StrUtil.isNotEmpty(lastToken)) {
            redisUtils.del(RedisKey.TOKEN_PREFIX + lastToken);
        }
        String token = JwtUtils.createToken(map, validityDuration);
        redisUtils.set(RedisKey.TOKEN_PREFIX + token, JSONUtil.toJsonStr(user), validityDuration);
        redisUtils.set(RedisKey.USER_LOGIN_PREFIX + user.getId(), token, validityDuration);
        return "Bearer " + token;
    }

    public static void deleteSessionInfo(AppClientUser user) {
        Map<String, String> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getNickname());
        String lastToken = redisUtils.get(RedisKey.USER_LOGIN_PREFIX + user.getId());
        if (StrUtil.isNotEmpty(lastToken)) {
            redisUtils.del(RedisKey.TOKEN_PREFIX + lastToken);
        }
        String token = JwtUtils.createToken(map, validityDuration);
        redisUtils.del(RedisKey.TOKEN_PREFIX + token);
        redisUtils.del(RedisKey.USER_LOGIN_PREFIX + user.getId());
    }


    public static AppClientUser getCurrentUser() {
        HttpServletRequest request = getRequest();
        String token = getAuthorization(request);
        log.info("redis中的token："+token);
        String userInfo = redisUtils.get(RedisKey.TOKEN_PREFIX + token);
        log.info("redis中的人员信息："+userInfo);
        if (StrUtil.isNotEmpty(userInfo)) {
            return JSONUtil.toBean(userInfo, AppClientUser.class);
        }
        return null;
    }

    public static String getCurrentUserId() {
        log.info("获取人员信息：");
        AppClientUser user = getCurrentUser();
        if (user != null) {
            return user.getId();
        }
        return null;
    }

    /**
     * 从 request 的 header 中获取 Authorization
     *
     * @param request 请求
     * @return JWT
     */
    public static String getAuthorization(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        log.info("获取人员信息：bearerToken："+bearerToken);
        if (StrUtil.isNotBlank(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }


    /**
     * 获取当前request
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }


}
